<?php

namespace app\common\model;

use app\common\library\Auth;
use think\Exception;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function money($money, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            $after = $user->money + $money;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 变更会员积分
     * @param int $score 积分
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /**
     * 更新微信用户
     * @param $wechatUser
     * @param $id
     * @return User|bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateWechatUser($wechatUser, $id)
    {
        $userInfo = self::where(['id' => $id])->find();
        if (!$userInfo) return false;
        Auth::instance()->login($userInfo['username'], 123456); // TODO 默认密码
        if ($userInfo['spread_id']) { // 已经有上级了
            return self::update([
                'nickname' => $wechatUser['nickname'] ?: '',
                'avatar' => $wechatUser['avatar'] ?: '',
                'login_type' => isset($wechatUser['login_type']) ? $wechatUser['login_type'] : $userInfo['login_type'],
            ], ['id' => $id]);
        } else { // 没有上级，则绑定上级
            $data = [
                'nickname' => $wechatUser['nickname'] ?: '',
                'avatar' => $wechatUser['avatar'] ?: '',
                'is_spreader' => $userInfo['is_spreader'],
                'login_type' => isset($wechatUser['login_type']) ? $wechatUser['login_type'] : $userInfo['login_type'],
                'spread_id' => 0,
                'spread_time' => 0,
                'logintime' => time(),
                'loginip' => request()->ip(),
            ];
            //TODO 获取后台分销类型 指定分销还是人人分销
            //$storeBrokerageStatus = SystemConfigService::get('store_brokerage_statu');
            //$storeBrokerageStatus = $storeBrokerageStatus ? $storeBrokerageStatus : 1;
            $storeBrokerageStatus = 0;
            if (isset($wechatUser['spread_code']) && $wechatUser['spread_code'] && $wechatUser['spread_code'] != $id && $id != self::where('id', '=', $wechatUser['spread_code'])->value('spread_id')) {
                if ($storeBrokerageStatus == 1) {
                    $spreadCount = self::where('id', $wechatUser['spread_code'])->count();
                    if ($spreadCount) {
                        $spreadInfo = self::where('id', $wechatUser['spread_code'])->find();
                        if ($spreadInfo['is_spreader']) {
                            //TODO 只有扫码才可以获得推广权限
//                            if(isset($wechatUser['isPromoter'])) $data['is_spreader'] = $wechatUser['is_spreader'] ? 1 : 0;
                        }
                    }
                }
                $data['spread_id'] = $wechatUser['spread_code'];
                $data['spread_time'] = time();
            }
            return self::update($data, ['id' => $id]);
        }
    }

    /**
     * 添加用户 如果有推广人，则绑定
     * @param $wechatUser
     * @param int $spread_id
     * @return User
     * @throws \think\exception\PDOException
     */
    public static function addWechatUser($wechatUser, $spread_id = 0)
    {
        self::startTrans();
        try {
            $res1 = true;
            if ($spread_id) $res1 = self::where('id', '=', $spread_id)->inc('spread_count', 1)->update();
//        $storeBrokerageStatu = SystemConfigService::get('store_brokerage_statu') ? : 1;//获取后台分销类型
            $res2 = [
                //'account' => 'wx' . $wechatUser['id'] . time(),
                //'pwd' => md5(123456),
                'nickname' => $wechatUser['nickname'] ?: '',
                'avatar' => $wechatUser['avatar'] ?: '',
                'spread_id' => $spread_id,
//            'is_spreader'=>$spread_id || $storeBrokerageStatu != 1 ? 1: 0,
                'spread_time' => $spread_id ? time() : 0,
                'id' => $wechatUser['id'],
                'joinip' => request()->ip(),
                'logintime' => time(),
                'loginip' => request()->ip(),
                'user_type' => $wechatUser['user_type']
            ];
            // 注册用户，进行登录
            Auth::instance()->register('wx' . $wechatUser['id'] . time(), 123456, '', '', $res2);
            self::commit();
            return $wechatUser['id'];
        } catch (Exception $exception) {
            self::rollback();
        }
    }
}
